package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerException(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage(),exception);
        if (exception.getMessage().contains("Duplicate entry")){
            String errorMessage = exception.getMessage().split(" ")[2];
            return R.error(errorMessage.replace(""," ")+"已存在");
        }
        return R.error("服务器异常,请稍后重试!");
    }

    /*@ExceptionHandler(Exception.class)
    public R handlerException(Exception exception){
        log.error(exception.getMessage(),exception);
        return R.error("服务器异常,请稍后重试!");
    }*/

    @ExceptionHandler(CustomException.class)
    public R handlerException(CustomException exception){
        log.error(exception.getMessage(),exception);
        return R.error(exception.getMessage());
    }

}
